package com.lm.scau.dyb.db.Dalx;

import android.content.ContentValues;
import android.database.Cursor;

import com.lm.scau.dyb.activity.base.BaseActivity;
import com.lm.scau.dyb.bean.PhotoWall;
import com.lm.scau.dyb.db.DybDB;
import com.lm.scau.dyb.utils.FlagHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/20.
 */
public class PhotoWallDalx extends BaseDalx {

    private static final String TB_NAME = "tb_photowall";
    private static final String PH_ID = "ph_id";
    private static final String PH_URL = "ph_url";
    private static final String PH_TIME = "ph_time";

    public PhotoWallDalx() {
    }

    public PhotoWallDalx(BaseActivity activity) {
        if (db == null) {
            db = DybDB.get(activity);
        }
        if (!db.tabbleIsExist(TB_NAME)) {
            createDataFileTable();
        }
    }

    public static void main(String args[]) {
        new PhotoWallDalx().createDataFileTable();
    }

    private void createDataFileTable() {
        String createTableSql = "CREATE TABLE IF NOT EXISTS " + TB_NAME + "(" + PH_ID
                + " varchar, " + PH_URL + " varchar, " + PH_TIME + " varchar)";
        db.creatTable(createTableSql);
    }

    /**
     * 获取最新的轮播时间，用来更新最新数据
     *
     * @return
     */
    @Override
    public String getLatelyTime() {
        String sql = "select " + PH_TIME + " from " + TB_NAME +
                " order by " + PH_TIME + " desc limit ?";
        Cursor cursor = db.find(sql, new String[]{"1"});
        String time = "1970-01-01 00:00:00";

        while (cursor.moveToNext()) {
            time = cursor.getString(cursor.getColumnIndex(PH_TIME));
            break;
        }
        return time;
    }

    /**
     * 新增轮播数据
     *
     * @param photoWall
     * @return
     */
    public boolean addPhotoWalls(PhotoWall photoWall) {
        boolean isOk = false;
        ContentValues values = new ContentValues();
        values.put(PH_ID, photoWall.getPhID());
        values.put(PH_URL, photoWall.getUrl());
        values.put(PH_TIME, photoWall.getTime());
        if (db.save(TB_NAME, values)) {
            isOk = true;
        }
        return isOk;
    }

    public List<String> getUrls() {
        List<String> urls =new ArrayList<>();
        String sql = "select " + PH_URL + " from " + TB_NAME +
                " order by " + PH_TIME + " desc limit ?";
        Cursor cursor = db.find(sql, new String[]{"5"});
        while (cursor.moveToNext()) {
            urls.add(FlagHelper.PHOTO_WALL_DIR+cursor.getString(cursor.getColumnIndex(PH_URL)));
        }
        return urls;
    }
}
